//
//  MBForumReleaseViewController.m
//  MiBaoTu
//
//  Created by admin on 16/10/17.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBForumReleaseViewController.h"
#import "MBLoginController.h"
#import "MBFeelView.h"
#import "AFNetworking.h"


#import "TZImagePickerController.h"

@interface MBForumReleaseViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate,UITextViewDelegate,TZImagePickerControllerDelegate> {
    UIScrollView                    *_scrollView;
    UITextField                     *_titleField;
    UIView                          *_contentView;
    //UITextView                      *_textView;
    MBFeelView                   *_textView;
    UIView                          *bottomView;
    float                           inputTime;
    float                           keyHeight;
    NSMutableArray                  *_imgMutArr;    //存储图片资源
    NSMutableArray                  *_imgUrlArr;    //存储图片地址
    NSMutableArray                  *_imgUrlUpdataArr; //保存未上传成功的图片数组
    NSMutableArray                  *_sensitiveArr;  //敏感词数组
}

@end
@implementation MBForumReleaseViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //释放
    [self removeForkeyboardNotifications];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _imgMutArr = [[NSMutableArray alloc]initWithCapacity:15];
    _imgUrlArr = [[NSMutableArray alloc]initWithObjects:@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@"", nil];
    _imgUrlUpdataArr = [[NSMutableArray alloc]init];
    NSString *SensitiveWordsPath = [[NSBundle mainBundle]pathForResource:@"SensitiveWords" ofType:@"txt"];
    NSString *SensitiveWordString = [NSString stringWithContentsOfFile:SensitiveWordsPath encoding:NSUTF8StringEncoding error:nil];
    NSArray *SensitiveWordArray = [SensitiveWordString componentsSeparatedByString:@"\r\n"];
    _sensitiveArr = [[NSMutableArray alloc]initWithArray:SensitiveWordArray];
    if (ISIPAD) {
        self.view.backgroundColor=UIColorFromHex(0xf5f5f5);
    }
    [self setNavBar];
    
    [self onCreateUI];
    
}

#pragma mark - UI
- (void)setNavBar
{
    [self setTitleView:@"写话题"];
    
    UIButton *lbt = [UIButton buttonWithType:UIButtonTypeCustom];
    lbt.frame = CGRectMake(0, 0, 60, 30);
    [lbt setTitle:@"取消" forState:UIControlStateNormal];
    [lbt setTitle:@"取消" forState:UIControlStateHighlighted];
    lbt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [lbt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
    [lbt addTarget:self action:@selector(onSelectItemForBack) forControlEvents:UIControlEventTouchUpInside];
    [self setLeftBarItem:lbt];
    
    UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
    bt.frame = CGRectMake(0, 0, 60, 30);
    [bt setTitle:@"发表" forState:UIControlStateNormal];
    [bt setTitle:@"发表" forState:UIControlStateHighlighted];
    bt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    [bt addTarget:self action:@selector(onSelectItemForFaBiao) forControlEvents:UIControlEventTouchUpInside];
    [self setRightBarItems:bt];
}

- (void)onCreateUI
{
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height-90*PERCEN)];
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapHideKeyWord)];
    [_scrollView addGestureRecognizer:tap];
    
    //标题
    UIView *_topView = [[UIView alloc]initWithFrame:CGRectMake(0, 20*PERCEN, _scrollView.width, 100*PERCEN)];
    if (ISIPAD) {
        _topView.frame=CGRectMake(0, 0, SCREEN_WIDTH, 160*PERCEN);
    }
    _topView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_topView];
    
    _titleField = [[UITextField alloc]initWithFrame:CGRectMake(25*PERCEN, (_topView.height-30)/2., _topView.width-2*25*PERCEN, 30)];
    if (ISIPAD) {
        _titleField.frame=CGRectMake(460*PERCEN, 20*PERCEN, SCREEN_WIDTH-2*460*PERCEN, 120*PERCEN);
    }
    _titleField.placeholder = @"请输入标题";
    _titleField.delegate = self;
    [_titleField setValue:[UIFont systemFontOfSize:14]forKeyPath:@"_placeholderLabel.font"];
    _titleField.font = [UIFont systemFontOfSize:14.f];
    
    _titleField.textAlignment = NSTextAlignmentLeft;
    _titleField.textColor = UIColorFromHex(0x333333);
    if (ISIPAD) {
        _titleField.font = [UIFont systemFontOfSize:28*PERCEN];
        _titleField.borderStyle = UITextBorderStyleRoundedRect;
    }
    [_topView addSubview:_titleField];
    
    //内容
    _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.bottom+20*PERCEN, _scrollView.width, SCREEN_HEIGHT-_topView.bottom-20*PERCEN-90*PERCEN-NAV_HEIGHT)];
    if (ISIPAD) {
        UIView *bgCView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.bottom+20*PERCEN, _scrollView.width, SCREEN_HEIGHT-_topView.bottom-20*PERCEN-90*PERCEN-NAV_HEIGHT)];
        bgCView.backgroundColor = [UIColor whiteColor];
        [_scrollView addSubview:bgCView];
        
        _contentView.frame=CGRectMake(_titleField.left, _topView.bottom+30*PERCEN, _titleField.width, 1068*PERCEN);
        _contentView.layer.cornerRadius = 5.;
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.borderColor = [UIColorFromHex(0x999999)colorWithAlphaComponent:.35].CGColor;
        _contentView.layer.borderWidth = 1;
    }
    _contentView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_contentView];
    
    UIFont *font = [UIFont systemFontOfSize:13.f];
    if (ISIPAD) {
        font=[UIFont systemFontOfSize:28*PERCEN];
    }
    _textView = [[MBFeelView alloc]initWithFrame:CGRectMake(20*PERCEN, 0, _contentView.width-2*20*PERCEN, _contentView.height)];
    if (ISIPAD) {
        _textView.frame=CGRectMake(20*PERCEN, 20*PERCEN, _contentView.width-40*PERCEN, 1018*PERCEN);
    }
    _textView.myPlaceholder = @"请输入内容,5000字以内";
    _textView.font = font;
    _textView.myPlaceholderColor = [UIColorFromHex(0x999999)colorWithAlphaComponent:.45];
    _textView.delegate = self;
    _textView.backgroundColor = [UIColor clearColor];
    [_contentView addSubview:_textView];
    
    //尾部
    bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height-90*PERCEN, _scrollView.width,90*PERCEN)];
    if (ISIPAD) {
        bottomView.frame=CGRectMake(0, SCREEN_HEIGHT-120*PERCEN, SCREEN_WIDTH, 120*PERCEN);
    }
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _scrollView.width,1)];
    lineView.backgroundColor = [UIColorFromHex(0xcccccc)colorWithAlphaComponent:1.];
    [bottomView addSubview:lineView];
    
    UIImage *img = [UIImage imageNamed:@"jiatu"];
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake((bottomView.width-img.size.width)/2., (bottomView.height-img.size.height)/2., img.size.width, img.size.height)];
    imgView.image = img;
    [bottomView addSubview:imgView];
    
    UIButton *_zhanKaiBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _zhanKaiBt.frame = bottomView.bounds;
    _zhanKaiBt.backgroundColor = [UIColor clearColor];
    [_zhanKaiBt addTarget:self action:@selector(onSelectForPicture) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:_zhanKaiBt];
}

- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShow:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
}

- (void)removeForkeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - Actions
- (void)onSelectItemForBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onTapHideKeyWord
{
    [self.view endEditing:YES];
}

#pragma mark -隐藏键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

- (void)keyboardWasShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    keyHeight = 0;
    if(kbSize.height == 216)
    {
        keyHeight = 0;
    }
    else
    {
        keyHeight = kbSize.height-216;   //258 - 216 系统键盘的两个不同高度
    }
    //输入框位置动画加载
    inputTime = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self onAnimationWithInputView:NO WithHeight:keyHeight WithDuration:inputTime];
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //do something
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"说点什么吧...";
        textView.textColor = [UIColorFromHex(0x999999)colorWithAlphaComponent:.45];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self onAnimationWithInputView:NO WithHeight:keyHeight WithDuration:inputTime];
    if ([textView.text isEqualToString:@"说点什么吧..."]) {
        textView.text = @"";
        textView.textColor = [UIColorFromHex(0x333333)colorWithAlphaComponent:1.];
    }
}

//输入框和遮挡层动画效果
- (void)onAnimationWithInputView:(BOOL)isHidden WithHeight:(float)heght WithDuration:(float)time
{
    [UIView animateWithDuration:time animations:^{
        bottomView.top = (isHidden == YES ? self.view.height-90*PERCEN : self.view.height-216-heght-90*PERCEN);
        _textView.height = (isHidden == YES ? _contentView.height:_contentView.height-216-heght);
    } completion:^(BOOL finished) {

    }];
}



#pragma mark - 选择照片
- (void)onSelectForPicture
{
    [self.view endEditing:YES];
    
    //判断
    NSString *textStr = [[self textStringWithSymbol:@"[图片]" attributeString:_textView.attributedText] mutableCopy];
    NSArray *picArr = [textStr componentsSeparatedByString:@"[图片]"];
    if ((picArr.count-1) >= 15) {
        [ErrorMessage showErrorMessage:@"最多只能上传15张照片" inView:self.view];
        return;
    }
    
    if (IOS(8.0)) {
        UIAlertController *alertContr = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        __weak typeof(self) weakSelf = self;
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf onChooseType:UIImagePickerControllerSourceTypeCamera];
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf onChooseType:UIImagePickerControllerSourceTypePhotoLibrary];
        }];
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertContr addAction:action1];
        [alertContr addAction:action2];
        [alertContr addAction:action3];
        [action1 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [action2 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        [action3 setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
        if (ISIPAD) {
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"打开照相机" otherButtonTitles:@"从手机相册获取", nil];
            [sheet showInView:self.view];
        } else {
            [self.navigationController presentViewController:alertContr animated:YES completion:NULL];
        }
    } else {
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"打开照相机" otherButtonTitles:@"从手机相册获取", nil];
        [sheet showInView:self.view];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (buttonIndex == 0) {
            [self onChooseType:UIImagePickerControllerSourceTypeCamera];
        }
        else if (buttonIndex == 1) {
            [self onChooseType:UIImagePickerControllerSourceTypePhotoLibrary];
        }
        else if (buttonIndex == 2) {
            
        }

    }];

    
  }

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    for (UIView *view in actionSheet.subviews) {
        if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)view;
            label.textColor = [UIColor blackColor];
        }
    }
}
#pragma mark--第三方相册协议
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets infos:(NSArray<NSDictionary *> *)infos{
    NSLog(@"info==%@",infos);
    if (photos.count>0) {

        for (UIImage *img in photos) {
            UIImage *originImg = [UIImage imageWithData:[self onGetPictureForIMG:img]];
            [_imgMutArr addObject:originImg];

        }
        
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            for (UIImage *originImg in _imgMutArr) {
                //将图片变成富文本
                NSTextAttachment *textAttachment = [[NSTextAttachment alloc]init];
                textAttachment.image = originImg;
                float itemCount = MIN(140*PERCEN/originImg.size.width, 140*PERCEN/originImg.size.height);
                CGRect rect = CGRectMake(0, 0, originImg.size.width*itemCount, originImg.size.height*itemCount);
                textAttachment.bounds = rect;//CGRectMake(0, 0, 140*PERCEN, 140*PERCEN);
                NSAttributedString *imageAttachment = [NSAttributedString attributedStringWithAttachment:textAttachment];
                NSMutableAttributedString *attriStr = [_textView.attributedText mutableCopy];
                [attriStr appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
                [attriStr appendAttributedString:imageAttachment];
                [attriStr appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
                _textView.attributedText = attriStr;
            }
          }];
      
    }
}
#pragma mark - 相片
- (void)onChooseType:(UIImagePickerControllerSourceType)sourceType
{
    
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
            NSLog(@"该手机不能拍照");
            return;
        }else{
            
        }
    } else {
        TZImagePickerController*pick=[[TZImagePickerController alloc]initWithMaxImagesCount:15 delegate:self];
        [pick setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets) {
            
        }];
        [self.navigationController presentViewController:pick animated:YES completion:nil];
        return;
    }
    
    UIImagePickerController *pickerCtrl = [[UIImagePickerController alloc]init];
    pickerCtrl.sourceType = sourceType;
    pickerCtrl.delegate = self;
//    pickerCtrl.allowsEditing = YES;allowsEditing
    if (ISIPAD) {
        pickerCtrl.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    if (ISIPAD) {
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            UIPopoverController *poc = [[UIPopoverController alloc]initWithContentViewController:pickerCtrl];
            poc.popoverContentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
            [poc presentPopoverFromRect:CGRectMake(0, bottomView.top, SCREEN_WIDTH, 1) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
        }];
    } else {
        [self.navigationController presentViewController:pickerCtrl animated:YES completion:NULL];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    if (info.count > 0) {
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            UIImage *originImg = [info objectForKey:UIImagePickerControllerEditedImage];
            UIImage *img = [UIImage imageWithData:[self onGetPictureForIMG:originImg]];
            [_imgMutArr addObject:img];
            
            //将图片变成富文本
            NSTextAttachment *textAttachment = [[NSTextAttachment alloc]init];
            textAttachment.image = img;
            textAttachment.bounds = CGRectMake(0, 0, 140*PERCEN, 140*PERCEN);
            NSAttributedString *imageAttachment = [NSAttributedString attributedStringWithAttachment:textAttachment];
            NSMutableAttributedString *attriStr = [_textView.attributedText mutableCopy];
            [attriStr appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            [attriStr appendAttributedString:imageAttachment];
            [attriStr appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            _textView.attributedText = attriStr;
        }];
    }
}

- (NSData *)onGetPictureForIMG:(UIImage *)img
{
    //尺寸压缩
    float itemCount = MIN(400/img.size.width, 400/img.size.height);
    
    CGRect rect = CGRectMake(0, 0, img.size.width*itemCount, img.size.height*itemCount);
    UIGraphicsBeginImageContext(rect.size);
    [img drawInRect:rect];
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImagePNGRepresentation(newImg);
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.navigationController dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - 发表
- (void)onSelectItemForFaBiao
{
    if (![UserManager standerDefult].userModel.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (_titleField.text.length == 0) {
        return;
    }
  
    
    if (_textView.attributedText.length > 0) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"发表话题...";
        [_imgUrlUpdataArr removeAllObjects];
        for (int i=0; i<_imgMutArr.count; i++) {
            //循环的作用是判断图片是否上传成功
            NSString *url = [_imgUrlArr objectAtIndex:i];
            if (url.length == 0) {
                [_imgUrlUpdataArr addObject:[NSNumber numberWithInt:i]];
            }
        }
        [self onLoadPicture:[[_imgUrlUpdataArr firstObject] intValue]];
    }
}
#pragma mark---正则过滤
- (NSString *)disable_emoji:(NSString *)text
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@""];
    return modifiedString;
}
- (void)onLoadPicture:(int)index
{
    if (_imgMutArr.count <= index) {
        //上传工作完成，不管上传是否成功
        NSString *textStr = [[self textStringWithSymbol:@"[图片]" attributeString:_textView.attributedText] mutableCopy];
        int index = 0;
        NSString *titleStr = _titleField.text;
        //通过替换
        if (textStr.length >= 4) {
            for (int i = 0; i <= textStr.length - 4; i ++) {
                NSString *tempStr = [textStr substringWithRange:NSMakeRange(i, 4)];
                if ([tempStr isEqualToString:@"[图片]"]) {
                    if ([_imgUrlArr[index] isEqualToString:@""]) {
                        [MBProgressHUD hideHUDForView:self.view animated:YES];
                        [ErrorMessage showErrorMessage:@"发表失败,请重试" inView:self.view];
                        return;
                    }
                    NSString *imgStr = [NSString stringWithFormat:@"<img src = '%@'/ width=\"100%%\">",_imgUrlArr[index]];
                    textStr = [textStr stringByReplacingCharactersInRange:NSMakeRange(i, 4) withString:imgStr];
                    index ++;
                }
            }
        }
        
        //敏感词过滤
        if (_sensitiveArr.count > 0) {
            NSMutableString *mutStr = [NSMutableString stringWithString:_titleField.text];
            NSMutableString *mutTextStr = [NSMutableString stringWithString:textStr];
            [_sensitiveArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([_titleField.text containsString:obj]) {
                    [mutStr replaceOccurrencesOfString:obj withString:@"**" options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutStr.length)];
                    
                }
                if ([mutTextStr containsString:obj]) {
                    [mutTextStr replaceOccurrencesOfString:obj withString:@"**" options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutTextStr.length)];
                }
            }];
            titleStr = (NSString *)mutStr;
            textStr = (NSString *)mutTextStr;
        }
        
        //表情 unicoke
        titleStr=[self disable_emoji:titleStr];
        textStr =[self disable_emoji:textStr];
//        return;
        NSString*url=[NSString stringWithFormat:FORUM_RELEASE_ACTIVITY_URL_PATH,[UserManager standerDefult].userModel.UserID,titleStr,textStr];
        NSLog(@"url===%@",url);
        [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(NSDictionary *json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([json isKindOfClass:[NSDictionary class]]) {
                if ([json[@"ret_code"] integerValue]==0) {
                    [ErrorMessage showErrorMessage:@"发表成功" inView:self.view];
                    [self back];
                }
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [ErrorMessage showErrorMessage:@"发表失败" inView:self.view];
            //清除数据，重新发布
            for (int i=0; i<_imgMutArr.count; i++) {
                [_imgUrlArr replaceObjectAtIndex:i withObject:@""];
            }
        }];

        
        return;
    }
    
    UIImage *img = [_imgMutArr objectAtIndex:index];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    [manager POST:[NSString stringWithFormat:UPLOAD_FILE_URL_PATH,[UserManager standerDefult].userModel.UserID] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImagePNGRepresentation(img);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"HeaderImg_%@.png",dateString];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"multipart/form-data"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            if ([[responseObject objectForKey:@"ret_code"]intValue] == 0) {
                NSString *webUrl = [responseObject objectForKey:@"web_url"];
                [_imgUrlArr replaceObjectAtIndex:index withObject:webUrl];
            } else {
                [_imgUrlArr replaceObjectAtIndex:index withObject:@""];
            }
            int newIndex = (int)[_imgUrlUpdataArr indexOfObject:[NSNumber numberWithInt:index]];
            if (newIndex+1 < _imgUrlUpdataArr.count) {
                int nextIndex = [[_imgUrlUpdataArr objectAtIndex:(newIndex+1)]intValue];
                [self onLoadPicture:nextIndex];
            } else {
                [self onLoadPicture:(newIndex+1)];
            }
         
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_imgUrlArr replaceObjectAtIndex:index withObject:@""];
        int newIndex = (int)[_imgUrlUpdataArr indexOfObject:[NSNumber numberWithInt:index]];
        if (newIndex < _imgUrlUpdataArr.count) {
            int nextIndex = [[_imgUrlUpdataArr objectAtIndex:(newIndex)]intValue];
            [self onLoadPicture:nextIndex];
        } else {
            [self onLoadPicture:(newIndex)];
        }
    }];
}

#pragma mark - 富文本转换操作
/** 将富文本转换为带有图片标志的纯文本*/
- (NSString *)textStringWithSymbol:(NSString *)symbol attributeString:(NSAttributedString *)attributeString{
    NSString *string = attributeString.string;
    string = [self stringDeleteString:@"\n" frontString:@"[图片]" inString:string];
    //最终纯文本
    NSMutableString *textString = [NSMutableString stringWithString:string];
    //替换下标的偏移量
    __block NSUInteger base = 0;
    
    //遍历
    [attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length)
                                options:0
                             usingBlock:^(id value, NSRange range, BOOL *stop) {
                                 //检查类型是否是自定义NSTextAttachment类
                                 if (value && [value isKindOfClass:[NSTextAttachment class]]) {
                                     //替换
                                     NSString *symbolStr = [NSString stringWithFormat:@"\n%@\n",symbol];
                                     [textString replaceCharactersInRange:NSMakeRange(range.location + base, range.length) withString:symbolStr];
                                     //增加偏移量
                                     base += (symbolStr.length - 1);
                                 }
                             }];
    return textString;
}
/** 删除字符串*/
- (NSString *)stringDeleteString:(NSString *)deleteString frontString:(NSString *)frontString inString:(NSString *)inString{
    NSArray *ranges = [self rangeOfSymbolString:frontString inString:inString];
    NSMutableString *mutableString = [inString mutableCopy];
    NSUInteger base = 0;
    for (NSString *rangeString in ranges) {
        NSRange range = NSRangeFromString(rangeString);
        [mutableString deleteCharactersInRange:NSMakeRange(range.location - deleteString.length + base, deleteString.length)];
        base -= deleteString.length;
    }
    return [mutableString copy];
}
/** 统计文本中所有图片资源标志的range*/
- (NSArray *)rangeOfSymbolString:(NSString *)symbol inString:(NSString *)string {
    NSMutableArray *rangeArray = [NSMutableArray array];
    NSString *string1 = [string stringByAppendingString:symbol];
    NSString *temp;
    for (int i = 0; i < string.length; i ++) {
        temp = [string1 substringWithRange:NSMakeRange(i, symbol.length)];
        if ([temp isEqualToString:symbol]) {
            NSRange range = {i, symbol.length};
            [rangeArray addObject:NSStringFromRange(range)];
        }
    }
    return rangeArray;
}


@end
